package main

import (
	"fmt"
	xls "github.com/shakinm/xlsReader/xls"

	xlsx "github.com/tealeg/xlsx/v3"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)
	//xls	"github.com/extrame/xls"   //解决不了GBK
	//xlsx	"github.com/tealeg/xlsx"
	//"github.com/xuancanh/xls"  使用表明无法正常读取数据
	//"github.com/extrame/xls"  使用表明无法正常读取数据


func main() {
    var xlsfilepath string
	if 2 == len(os.Args) {
		xlsfilepath = os.Args[1]
	} else if 2 != len(os.Args){
		xlsfilepath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
		log.Print("\n---------------------------------------------------\n批量转换xls文件为xlsx\t作者：jordan QQ 87895224\n\n放到xls文件所在目录，双击执行\n\n也可以命令行执行：\nxls2xlsx <xls文件所在路径>  \n---------------------------------------------------\n")
	}
	os.Chdir(xlsfilepath)

    // 遍历目录
	fss := curpathfiles(xlsfilepath)
	for _,s:= range (*fss){
		fmt.Println(s)
		xls2xlsx(s,xlsfilepath)
	}
	log.Println("byebye")
}
func curpathfiles(pathname string) *[]string {

	rd, err := ioutil.ReadDir(pathname)
	if err !=nil{log.Println(err)}

	var filenames []string
	var validID = regexp.MustCompile(`(\.xls)$`)

	for _, fi := range rd {
		if fi.IsDir() {

		} else if validID.MatchString (fi.Name()) {
			filenames = append(filenames,fi.Name())
		}
	}
	return &filenames
}
func xls2xlsx(xlsfile string,pth string)  {
	wb1,err :=xls.OpenFile(xlsfile);logoute(err)
    fn:=strings.TrimSuffix(xlsfile,".xls")
	newfilename :=fn +".xlsx"

	f2:= xlsx.NewFile()
	for i:=0;i <wb1.GetNumberSheets();i++{

		ws1,_:=wb1.GetSheet(i)
		s2,err :=f2.AddSheet(ws1.GetName());logoute(err)
		maxrows:=ws1.GetNumberRows()
		fmt.Printf("\n表%d[%s] 总行%d\n",i+1,ws1.GetName(),maxrows)
		for r:=0;r<maxrows;r++ {
			r2:=s2.AddRow()
			r1,_:=ws1.GetRow(int(r))

			cols := r1.GetCols()
			for _,cs :=range cols {
				c2 := r2.AddCell()
				c2.SetValue(cs.GetString())
				}
			//fmt.Printf("\r%s",strings.Repeat(" ",100))
			fmt.Printf("\r表%d 行%d 百分比 %.2f%%",i+1,r+1,float32(100.0*(r+1.0000))/float32(maxrows))

		}
	}
	fmt.Println("")
	log.Printf("%s 转换完成,正在保存\n",newfilename)
	f2.Save(newfilename)

}
func logoute(e error)  {
	if e !=nil{
		log.Fatal("异常",e)
	}

}